import { Line } from 'react-chartjs-2'
import './setup' // 确保Chart.js组件被注册
import { commonOptions, colors, createGradient } from './chartConfig'

interface TimeTrend {
  date: string
  created: number
  completed: number
}

interface TimeTrendsChartProps {
  data: TimeTrend[]
  selectedPeriod: number
}

export default function TimeTrendsChart({ data, selectedPeriod }: TimeTrendsChartProps) {
  // 处理数据，确保有足够的数据点
  const processedData = data.slice(-selectedPeriod).map(trend => ({
    ...trend,
    date: new Date(trend.date).toLocaleDateString('zh-CN', { 
      month: 'short', 
      day: 'numeric' 
    })
  }))

  const chartData = {
    labels: processedData.map(item => item.date),
    datasets: [
      {
        label: '创建任务',
        data: processedData.map(item => item.created),
        borderColor: colors.primary.border,
        backgroundColor: (context: any) => {
          const chart = context.chart
          const { ctx, chartArea } = chart
          if (!chartArea) return colors.primary.bg
          return createGradient(ctx, colors.primary.gradient)
        },
        fill: true,
        tension: 0.4,
        pointBackgroundColor: colors.primary.border,
        pointBorderColor: '#ffffff',
        pointBorderWidth: 2,
        pointRadius: 4,
        pointHoverRadius: 6
      },
      {
        label: '完成任务',
        data: processedData.map(item => item.completed),
        borderColor: colors.success.border,
        backgroundColor: (context: any) => {
          const chart = context.chart
          const { ctx, chartArea } = chart
          if (!chartArea) return colors.success.bg
          return createGradient(ctx, colors.success.gradient)
        },
        fill: true,
        tension: 0.4,
        pointBackgroundColor: colors.success.border,
        pointBorderColor: '#ffffff',
        pointBorderWidth: 2,
        pointRadius: 4,
        pointHoverRadius: 6
      }
    ]
  }

  const options = {
    ...commonOptions,
    plugins: {
      ...commonOptions.plugins,
      title: {
        display: false
      }
    },
    scales: {
      ...commonOptions.scales,
      y: {
        ...commonOptions.scales?.y,
        beginAtZero: true,
        ticks: {
          ...commonOptions.scales?.y?.ticks,
          stepSize: 1
        }
      }
    },
    interaction: {
      intersect: false,
      mode: 'index' as const
    }
  }

  if (processedData.length === 0) {
    return (
      <div className="h-64 flex items-center justify-center text-theme-text-muted">
        <div className="text-center">
          <div className="w-16 h-16 bg-theme-bg-tertiary rounded-full flex items-center justify-center mx-auto mb-3">
            📊
          </div>
          <p>暂无趋势数据</p>
        </div>
      </div>
    )
  }

  return (
    <div className="h-64">
      <Line data={chartData} options={options} />
    </div>
  )
}
